package com.youcai.springbootshiro.config;

import com.youcai.springbootshiro.entity.Student;
import com.youcai.springbootshiro.service.StudentService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    StudentService studentService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //给用户授权
//        simpleAuthorizationInfo.addStringPermission("user:add");


        //拿到当前对象
        Subject subject = SecurityUtils.getSubject();
        Student student= (Student) subject.getPrincipal();
        //设置当前用户的权限
        simpleAuthorizationInfo.addStringPermission(student.getPerms());

        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        //连接数据库
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        /*String name = "admin";
        String pass = "123456";*/
         Student student = studentService.queryStudent(usernamePasswordToken.getUsername());

        if (student == null){
            return null;
        }

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("student",student);


        return new SimpleAuthenticationInfo(student,student.getSpass(),"") ;
    }
}
